import 'dart:io';

import 'package:applovin_max/applovin_max.dart';
import 'package:bitcoin_mine/api/api.dart';
import 'package:bitcoin_mine/common/global.dart';
import 'package:get/get_rx/src/rx_types/rx_types.dart';
import 'package:get/get_state_manager/src/simple/get_controllers.dart';

import '../http/http_request.dart';
import '../model/contract.dart';

class ContractServiceController extends GetxController {
  static final String _rewarded_ad_unit_ID =
      Platform.isAndroid ? "«Android-ad-unit-ID»" : "06720d165426bdfa";
  final int _maxExponentialRetryCount = 6;
  static var _rewardedAdRetryAttempt = 0;

  RxBool adLoading = false.obs;

  @override
  void onInit() {
    super.onInit();
    initRewardedAd();
  }

  // 观看广告
  Future<void> watchAds() async {
    if (adLoading.value) {
      print('广告正在加载中');
      return;
    }
    print('广告开始加载');
    adLoading.value = true;
    bool isReady = (await AppLovinMAX.isRewardedAdReady(_rewarded_ad_unit_ID))!;
    if (isReady) {
      AppLovinMAX.showRewardedAd(_rewarded_ad_unit_ID);
    } else {
      // Fluttertoast.showToast(msg: '广告未准备好');
      loadRewardedAd(playNow: true);
    }

    // HttpRequest.instance.requestCommon("GET", Api.receiveAdContract).then((
    //   value,
    // ) {
    //   if (value != null) {
    //     print('观看广告成功: $value');
    //   }
    // });
  }

  // 领取免费合约
  Future<void> receiveFreeContract() async {
    await HttpRequest.instance.requestNetwork<List<Contract>>(
      Api.receiveFreeContract,
      method: "GET",
      onSuccess: (data) {
        if (data != null) {
          Global.contracts.value = data;
          Global.updateTotalHashrate();
          print('领取免费合约成功: ${Global.contracts.length}');
        }
        return data;
      },
    );
  }

  Future<void> initRewardedAd() async {
    loadRewardedAd(playNow: false);
  }

  void loadRewardedAd({bool playNow = false}) {
    if (Global.isAppLovinMAXInitialized) {
      AppLovinMAX.setRewardedAdListener(
        RewardedAdListener(
          onAdLoadedCallback: (ad) async {
            // Rewarded ad is ready to show. AppLovinMAX.isRewardedAdReady(_rewarded_ad_unit_ID) now returns 'true'.
            print('Rewarded ad loaded from $ad');

            // Reset retry attempt
            _rewardedAdRetryAttempt = 0;
            if (playNow) {
              showRewardedAd();
            } else {
              adLoading.value = false;
            }
          },
          onAdLoadFailedCallback: (adUnitId, error) {
            // Rewarded ad failed to load.
            // AppLovin recommends that you retry with exponentially higher delays up to a maximum delay (in this case 64 seconds).
            // _rewardedAdRetryAttempt = _rewardedAdRetryAttempt + 1;
            // if (_rewardedAdRetryAttempt > _maxExponentialRetryCount) return;
            // int retryDelay =
            //     pow(
            //       2,
            //       min(_maxExponentialRetryCount, _rewardedAdRetryAttempt),
            //     ).toInt();
            print(
              'Rewarded ad failed to load with code ${error.code} - ${error.message}',
            );
            adLoading.value = false;

            // Future.delayed(Duration(milliseconds: retryDelay * 1000), () {
            // loadRewardedAd();
            // });
          },
          onAdDisplayedCallback: (ad) {},
          onAdDisplayFailedCallback: (ad, error) {},
          onAdClickedCallback: (ad) {},
          onAdHiddenCallback: (ad) {},
          onAdReceivedRewardCallback: (ad, reward) async {
            print('观看广告成功 $reward');
            await HttpRequest.instance.requestNetwork<List<Contract>>(
              Api.receiveAdContract,
              method: "GET",
              onSuccess: (data) async {
                if (data != null) {
                  Global.contracts.value = data;
                  Global.updateTotalHashrate();
                  print('观看广告成功: ${Global.contracts.length}');
                }
                adLoading.value = false;
                return data;
              },
              onError: (error, msg) {
                adLoading.value = false;
              },
            );
          },
        ),
      );
      AppLovinMAX.loadRewardedAd(_rewarded_ad_unit_ID);
    }
  }

  void showRewardedAd() async {
    bool isReady = (await AppLovinMAX.isRewardedAdReady(_rewarded_ad_unit_ID))!;
    if (isReady) {
      AppLovinMAX.showRewardedAd(_rewarded_ad_unit_ID);
    }
  }
}
